<?php

namespace app\middleware;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;

use think\facade\Log;
class Check
{
    /**
     * 权限校验中间件
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     */
    public function handle($request, \Closure $next)
    {
        $header = $request->header();

        if (empty($header['authorization'])) {
            return result(RESULT_FAILED,'','Token不存在');
        } else {
            $checkJwtToken = $this->verifyJwt($header['authorization']);
            if ($checkJwtToken['code'] == RESULT_SUCCESS) {
                return $next($request);
            }
            return result($checkJwtToken['code'],'',$checkJwtToken['msg']);


        }
    }

    /**
     * 校验jwt权限API
     * @param $jwt
     * @return array
     */
    protected function verifyJwt($jwt)
    {

        $key = md5('gaojian');
        try {

            $jwtAuth = json_encode(JWT::decode($jwt, $key, array('HS256')));


            $authInfo = json_decode($jwtAuth, true);
            if (!empty($authInfo['user_id'])) {
                $msg = [
                    'code' => RESULT_SUCCESS,
                    'msg' => 'Token验证通过'
                ];
            } else {
                $msg = [
                    'code' => RESULT_FAILED,
                    'msg' => 'Token验证不通过,用户不存在'
                ];
            }
            return $msg;
        } catch (SignatureInvalidException $e) {
            $msg = [
                'code' => RESULT_FAILED,
                'msg' => 'Token无效'
            ];
            return $msg;
        } catch (ExpiredException $e) {
            $msg = [
                'code' => RESULT_FAILED,
                'msg' => 'Token过期'
            ];
            return $msg;
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            $msg = [
                'code' => RESULT_FAILED,
                'msg' => '验证失败'
            ];
            return $msg;
        }
    }
}
